<template>
  <div class="app-container">
  <el-descriptions class="margin-top" title="" :column="3" :size="'mini'" border>
    <el-descriptions-item>
      <template slot="label">
        <i class="el-icon-user"></i>
        采购计划
      </template>
      {{this.purchase.name}}
    </el-descriptions-item>
    <el-descriptions-item>
      <template slot="label">
        <i class="el-icon-location-outline"></i>
        截止时间
      </template>
      {{this.purchase.dueTime}}
    </el-descriptions-item>
    <el-descriptions-item>
      <template slot="label">
        <i class="el-icon-mobile-phone"></i>
        采购需求
      </template>
          <el-tooltip class="item" effect="dark" :content="this.purchase.needHerb" placement="top-start">
            <span>{{ellipsis(this.purchase.needHerb)}}</span>
          </el-tooltip>
    </el-descriptions-item>
    <el-descriptions-item>
      <template slot="label">
        <i class="el-icon-tickets"></i>
        联系人
      </template>
      {{this.purchase.contactName}}
    </el-descriptions-item>
    <el-descriptions-item>
      <template slot="label">
        <i class="el-icon-office-building"></i>
        电话
      </template>
      {{this.purchase.contactTel}}
    </el-descriptions-item>
    <el-descriptions-item>
      <template slot="label">
        <i class="el-icon-office-building"></i>
        发布时间
      </template>
      {{this.purchase.addTime}}
    </el-descriptions-item>
  </el-descriptions>

  <el-tabs v-model="activeIndex" type="card" @tab-click="handleClick">
    <el-tab-pane label="报价中" name="1" style="width: 25%;"></el-tab-pane>
    <el-tab-pane label="已报价" name="2" style="width: 25%;"></el-tab-pane>
    <el-tab-pane label="已中标" name="3" style="width: 25%;"></el-tab-pane>
    <el-tab-pane label="已结束" name="4" style="width: 25%;"></el-tab-pane>
  </el-tabs>

    <div class="filter-container">
      <!-- <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleDownload()">导出</el-button> -->
      <el-button class="filter-item" type="primary" icon="el-icon-d-arrow-right" @click="winBidding()">中标</el-button>
    </div>
  
  <el-table v-loading="listLoading" :data="purchaseManage" element-loading-text="正在查询中。。。" @selection-change="handleSelectionChange" border fit highlight-current-row>
    <el-table-column
        type="selection"
        width="50"
        :selectable="selectable"
        align="center"
        fixed="left"
        :resizable="false"
      />
      <el-table-column align="center" label="编号" prop="code" />
      <el-table-column align="center" label="药材名" prop="herbName" />
      <el-table-column align="center" label="规格" prop="specifications" />
      <el-table-column align="center" label="需求数量" prop="needAmount" />
      <el-table-column align="center" label="单位" prop="measurementUnit" />
      <el-table-column align="center" label="预计到货时间" prop="inspectionCompletionTime" width="170px">
        <template slot-scope="scope">
         <div class="block">
          <el-date-picker
            style="width: 90%;"
            v-model="scope.row.inspectionCompletionTime"
            align="right"
            type="date"
            value-format="yyyy-MM-dd HH:mm:ss"
            default-time="12:00:00"
            placeholder="选择日期"
            :picker-options="pickerOptions">
          </el-date-picker>
         </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="供应商" prop="companyName" />
      <el-table-column align="center" label="供应商电话" prop="supplyContactTel" />
      <el-table-column align="center" label="报价(元)" prop="supplyPrice" />
      <el-table-column align="center" label="图片" prop="specificationsImage" >
        <template slot-scope="scope">
          <el-image :src="thumbnail(scope.row.specificationsImage)" :preview-src-list="toPreview(scope.row, scope.row.specificationsImage)" style="width: 50px; height: 50px" />
        </template>
      </el-table-column>


      <el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleView(scope.row,scope.$index)">更换供应商</el-button>
        </template>
      </el-table-column>
    </el-table>


 <!-- 添加或修改对话框 -->
    <el-dialog :title="'更换供应商'" :visible.sync="dialogFormVisible">
    
        <!-- 查询结果 -->

      <div class="filter-container">
      <el-input v-model="queryQuery.contactTel" clearable class="filter-item" style="width: 160px;" placeholder="联系电话" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="queryQuoteDetails()">查找</el-button>
      </div>
    <el-table v-loading="listLoading" :data="shopList" element-loading-text="正在查询中。。。" border fit highlight-current-row>


      <el-table-column align="center" label="商户类型" prop="userType">
        <template slot-scope="scope">
          {{ levelDic[scope.row.userType] }}
        </template>
      </el-table-column>

      <el-table-column align="center" label="商户名" prop="companyName" />
      
      <el-table-column align="center" label="联系人" prop="contactName" />
      
      <el-table-column align="center" label="电话" prop="contactTel" />
      
      <el-table-column align="center" label="报价(元)" prop="supplyPrice" />

      <el-table-column align="center" label="图片" prop="specificationsImage" >
        <template slot-scope="scope">
          <!-- <img :src="scope.row.specificationsImage" class="avatar" style="width: 70px;"> -->
          <el-image :src="thumbnail(scope.row.specificationsImage)" :preview-src-list="toPreview(scope.row, scope.row.specificationsImage)" style="width: 70px; height: 70px" />
        </template>
      </el-table-column>


       <el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
        
      <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="replace(scope.row)">更换</el-button>
        </template>
      </el-table-column>

    </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>


<style>

</style>

<script>
import { fetchPurchaseAndItemList,queryQuoteDetails ,winBidding } from '@/api/purchaseManage'
import { uploadPath } from '@/api/storage'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { thumbnail, toPreview } from '@/utils/index'

export default {
  name: 'hasQuotation',
  components: { Pagination },
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 3600 * 1000 * 24;
        },
      },
      thumbnail,
      toPreview,
      id:'',
      uploadPath,
      itemId:'',
      index:'',
      measurementUnit:'',
      activeIndex: '2',
      purchase:{},
      purchaseManage: [],
      levelDic: ['个人', '饮片厂', '经销商'],
      listLoading: true,
      dialogFormVisible:false,
      has: 'primary',
      not: 'default',
      shopList:[],
      selectList:[],
      type:0,
      queryQuery: {
        purchaseId:'',
 
      },
      listQuery: {
        page: 1,
        limit: 20,
        type: 1,
        remark:'',
        status:'2',
        id: undefined,
        name: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      statusDic: {
        2:'已发布'
      }
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    // 绑定enter事件
    this.enterKeyup();
  },
  destroyed() {
    // 销毁enter事件
    this.enterKeyupDestroyed();
  },
  methods: {
    enterKey(event) {
      if(event.key=='Enter'){
        this.queryQuoteDetails()
      }
    },
    
    enterKeyupDestroyed() {
        document.removeEventListener("keyup", this.enterKey);
    },
    enterKeyup() {
        document.addEventListener("keyup", this.enterKey);
    },
    getList() {
      this.id=this.$route.query.id
      this.listQuery.id=this.$route.query.id
      this.listLoading = true
      fetchPurchaseAndItemList(this.listQuery)
        .then(response => {
          this.purchase = response.data.data.purchase
          this.purchaseManage = response.data.data.purchaseManage
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.listLoading = false
        })
    },
    handleView(row,index){
      this.dialogFormVisible = true
      this.index=index
      this.itemId=row.id
      this.measurementUnit=row.measurementUnit
      this.queryQuery.purchaseId=this.itemId
      this.queryQuoteDetails()
    },
        handleClick(tab, event) {
          if(tab.name==1){
          this.$store.dispatch('tagsView/delView', this.$route)
          this.$router.push({ path: '/mall/noQuotation', query: { id: this.id }})
        }else if(tab.name==2){
          this.$store.dispatch('tagsView/delView', this.$route)
          this.$router.push({ path: '/mall/hasQuotation', query: { id: this.id }})
        }else if(tab.name==3){
          this.$store.dispatch('tagsView/delView', this.$route)
          this.$router.push({ path: '/mall/winBidding', query: { id: this.id }})
        }else if(tab.name==4){
          this.$store.dispatch('tagsView/delView', this.$route)
          this.$router.push({ path: '/mall/finish', query: { id: this.id }})
        }
      },
      selectable(row) {
      if (row.bytstatus === 4) {
        return false
      } else {
        return true
      }
    },
     // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectList = selection
    },
    queryQuoteDetails(){
      this.listLoading = true
      queryQuoteDetails(this.queryQuery)
        .then(response => {
          this.shopList = response.data.data
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.listLoading = false
        })
    },
    ellipsis (value) {
      if (!value) return ''
      if (value.length > 20) {
        return value.slice(0,20) + '...'
      }
      return value
    },
    winBidding(){
      console.log(this.selectList)
      if(this.selectList.length!=0){
        if (
          !this.selectList.findIndex(
            (arr) =>
              arr.inspectionCompletionTime != undefined &&
              arr.inspectionCompletionTime != "" &&
              arr.inspectionCompletionTime != 0
          )
        ) {
          this.$confirm('是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            winBidding(this.selectList).then(response => {
              this.$notify.success({
                title: '成功'
              })
                this.getList()
              }).catch(() => {
                this.$notify.error({
                  title: '失败'
                })
                this.downloadLoading = false
            })
            }).catch(() => {
              this.stepLoading = false
              this.$message({
                type: 'info',
                message: '已取消'
              });          
            });
        } else {
          this.$message({
            message: "请检查预计到货日期是否正确,且不能为空",
            type: "warning",
          });
        }
      }else {
        this.$message({
          message: "请至少选择一个",
          type: "warning",
        });
      }
    },
    replace(row){
      this.purchaseManage[this.index].priceId=row.quoteId
      this.purchaseManage[this.index].supplyShopId=row.id
      this.purchaseManage[this.index].companyName=row.companyName
      this.purchaseManage[this.index].supplyContactTel=row.contactTel
      this.purchaseManage[this.index].supplyPrice=row.supplyPrice
      this.purchaseManage[this.index].specificationsImage=row.specificationsImage
      this.dialogFormVisible = false
    },
    // 导出的方法
    handleDownload() {
      this.downloadLoading = true
      this.listQuery.selectAll = true
      fetchPurchaseAndItemList(this.listQuery).then(response => {
        require.ensure([], () => {
          const { export_json_to_excel } = require('../../vendor/Export2Excel')// 注意这个Export2Excel路径
          const tHeader = ['药材编号', '药材名称','规格','单位','需求数量','已报价供应商数','未报价供应商数'] // 上面设置Excel的表格第一行的标题
          const filterVal = ['code', 'herbName','specifications', 'measurementUnit','needAmount','yet','sum'] // 上面的index、nickName、name是tableData里对象的属性key值
          const list = response.data.data.list // 把要导出的数据tableData存到list
          const data = this.formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, flag?'药材品类信息':'药材品类导入模板')// 最后一个是表名字
        })
        this.downloadLoading = false
      }).catch(() => {
        this.$notify.error({
          title: '导出失败'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    }

  }
}
</script>
